const app = getApp()
const {
  upTime
} = require('/util/public')
const {
  activeProMoney
} = require("/util/handler_page/activeProduct")
Page({
  data: {
    types: [{
        title: '全部',
        state: -1,
        order: [],
        totalResult: null,
        page: 1
      },
      {
        title: '待付款',
        state: 1,
        order: [],
        totalResult: null,
        page: 1
      },
      {
        title: '待发货',
        state: 3,
        order: [],
        totalResult: null,
        page: 1
      },
      {
        title: '待收货',
        state: 4,
        order: [],
        totalResult: null,
        page: 1
      },
      {
        title: '待归还',
        state: 5,
        order: [],
        totalResult: null,
        page: 1
      },
      {
        title: '已完成',
        state: 7,
        order: [],
        totalResult: null,
        page: 1
      },
      {
        title: '申请取消',
        state: 14,
        order: [],
        totalResult: null,
        page: 1
      }
    ],
    activeTab: 0,
    status: ['', "待付款", "待审核", "待发货", "待收货", "待归还", "", "交易完成", "完结订单", "订单关闭（用户）", "订单关闭（系统）", "订单关闭（商家）", "已完成", '即将到期', '申请取消'],

    totalPage: null,
    onPull: false,
  },
  onLoad(query) {
    if (query.param) {
      let index = JSON.parse(query.param)
      this.handleTabClick({
        index: index,
        tabsName: 'activeTab'
      })
    } else {
      let index = 0;
      this.handleTabClick({
        index: index,
        tabsName: 'activeTab'
      })
    };
    app._init_(this);

    console.log("11111111111")

  },
  onShow() {
    const onPull = this.data.onPull
    if (onPull) {
      console.log("刷新=======================》》》》")
      this.onPullDownRefresh()
      this.data.onPull = false
    }
  },
  onHide() {
    this.setData({
      onPull: true
    })
  },

  // tabs
  handleTabClick({
    index = 0,
    tabsName
  }) {
    this.setData({
      [tabsName]: index,
    });
    const types = this.data.types;
    if (types[index].totalResult == null) {
      this.get_meg()
    }
    // this.get_meg()
  },

  // 获取数据
  get_meg() {
    this.setData({
      show: true
    });
    const types = this.data.types;
    let data = {
      status: types[this.data.activeTab].state,
      page: types[this.data.activeTab].page,
      rows: 10,
    }
    app.order.page(data)
      .then(res => {
        console.log("数据", res)
        res.data.list.forEach(async (item) => {

          item.paramsOld = item.params;
          item.params = JSON.parse(item.params);
          item.createtime = upTime("%Y-%M-%D %h:%m:%h", item.createtime);
          item.starttime = item.starttime ? upTime("%Y-%M-%D", item.starttime) : '';
          item.endtime = item.endtime ? upTime("%Y-%M-%D", item.endtime) : '';
          item = await activeProMoney(item)
          if (item.status == 4 && item.productOrderShipment != null) {
            item.flowOne = {
              id: item.id,
              receiverPhone: item.phone.slice(-4, item.phone.length),
              com: item.productOrderShipment.company,
              no: item.productOrderShipment.number,
            }
          } else if (item.status == 6 && item.productOrderRecycle != null) {
            item.flowOne = {
              id: item.id,
              receiverPhone: item.shopsVo.phone.slice(-4, item.phone.length),
              com: item.productOrderRecycle.company,
              no: item.productOrderRecycle.number,
            }
          } else {
            item.flowOne = null
          }
        })
        types[this.data.activeTab].order = [...types[this.data.activeTab].order, ...res.data.list]
        types[this.data.activeTab].totalResult = res.data.totalResult
        this.setData({
          types
        })
        setTimeout(() => {
          this.setData({
            show: false
          });
        }, 200)
      }, err => {
        my.switchTab({
          url: '/pages/main/my/my'
        })
      })

  },

  // btn 订单按钮
  //   联系商家
  makePhoneCall(e) {
    // console.log(e.target.dataset.phone)
    let phone = e.target.dataset.phone;
    my.makePhoneCall({
      number: phone
    });
  },
  // 关闭订单
  onCancel(e) {
    // console.log(e.target.dataset.item)
    let id = e.target.dataset.item.id;
    let status = e.target.dataset.item.status;
    my.prompt({
      title: '申请取消',
      message: '请输入取消原因',
      placeholder: '请输入取消原因',
      okButtonText: '确定',
      cancelButtonText: '取消',
      success: (result) => {
        console.log(result)
        if (!result.ok) {
          return
        }
        if (result.inputValue) {
          if (status == 1) {
            app.order.canOrder(id, {
                cont: result.inputValue
              })
              .then((res) => {
                my.alert({
                  title: "取消成功",
                  success: () => {
                    this.resetOrder()
                  }
                });
              })
          } else if (status == 2) {
            app.order.canOrder(id, {
                cont: result.inputValue
              })
              .then((res) => {
                console.log(res)
                my.alert({
                  title: "申请成功",
                  success: () => {
                    this.resetOrder()
                  }
                });

              })
          }
        } else {
          my.showToast({
            type: 'exception',
            content: '请输入取消原因',
          });
        }
      },
    });
  },
  // 撤销申请
  noCancel(e) {
    let cancelRequests = e.target.dataset.item.productOrderCancelRequests
    let id = cancelRequests[cancelRequests.length - 1].id
    my.confirm({
      title: '温馨提示',
      content: '是否撤回订单取消申请',
      confirmButtonText: '立即撤回',
      cancelButtonText: '暂不撤回',
      success: (result) => {
        if (result.confirm) {
          app.order.canOrder(id)
            .then(red => {
              if (res.code == 200) {
                my.alert({
                  title: "撤回成功",
                  success: () => {
                    this.resetOrder()
                  }

                });
              }
            })
        }
      },
    });
  },

  // 冻结
  onBuy(e) {
    let that = this
    const data = e.target.dataset.data;
    app.order.freeze(data.id)
      .then(pay => {
        my.tradePay({
          orderStr: pay.data, // 完整的支付参数拼接成的字符串，从服务端获取
          success: (res) => {
            console.log(res)
            if (res.resultCode == 9000) {
              my.alert({
                content: "支付成功",
              });
              this.resetOrder()
            }
          },
          fail: (res) => {
            my.alert({
              content: res.memo,
            });
          }
        });
      })
  },
  // 支付
  onReplenish(e) {
    let that = this
    let oid = e.target.dataset.data.productOrderRecordVoList[0].oid
    let id = e.target.dataset.data.productOrderRecordVoList[0].id
    app.order.alipay(oid, id)
      .then(res => {
        my.tradePay({
          tradeNO: res.data,
          success: function (res) {
            // console.log(res)
            if (res.resultCode == 9000) {
              my.alert({
                content: "支付成功",
              });
              this.resetOrder()
            } else {
              my.alert({
                content: res.memo,
              });
            }
          },

        });
      })
  },
  // 确认收货
  ConfirmReceipt(e) {
    let id = e.target.dataset.id
    app.order.receiving(id)
      .then(res => {
        if (res.code == 200) {
          my.alert({
            content: "提交成功",
            success: () => {
              this.resetOrder()
            }
          })
        } else {
          my.alert({
            content: res.msg
          })
        }
      })
  },

  // 买断
  buyoutBtn(options) {
    my.confirm({
      title: '温馨提示',
      content: '确定要买断吗？买断后需支付剩余尾款。',
      confirmButtonText: '马上买断',
      cancelButtonText: '暂不需要',
      success: (result) => {
        if (result.confirm) {
          console.log("11111111111111", options.target.dataset.param.id)
          const oid = options.target.dataset.param.id;
          app.order.buyout(oid)
            .then(res => {
              console.log("返回消息", res)

              if (!res.data) {
                my.showToast({
                  content: '请联系客服买断！',
                });
                return;
              }
              app.alipay(res.data).then(pay => {
                if (pay.resultCode == 9000) {
                  my.showToast({
                    content: '支付成功',
                  });
                }
              })
            })
        }

      }
    })
  },

  // 跳转
  navigateTo(e) {
    app.navigateTo(e)
  },

  // 重置订单列表
  resetOrder() {
    const types = this.data.types;
    const tabIndex = this.data.activeTab;
    types[tabIndex].order = [];
    types[tabIndex].page = 1;
    types[tabIndex].totalResult = null;
    this.setData({
      types
    });
    this.onLoad({
      param: this.data.activeTab
    });
  },

  // 下拉刷新
  onPullDownRefresh() {
    this.resetOrder()
    setTimeout(() => {
      my.stopPullDownRefresh({
        complete(res) {}
      })
    }, 1000)
  },
  stopPullDownRefresh() {
    my.stopPullDownRefresh({
      complete(res) {
        // console.log(res, new Date())
      }
    })
  },
  //   下拉加载
  onReachBottom() {
    const that = this
    const types = this.data.types;
    const tabIndex = this.data.activeTab
    try {
      // 判断是否还有数据需要加载
      if (types[tabIndex].order.length < types[tabIndex].totalResult) {
        types[tabIndex].page++
        that.get_meg();
      }
    } catch (e) {}
  },

  signClick(e) {
    app.order.sign(e.target.dataset.id)
      .then(res => {
        console.log("================>>签署协议", res)
        this.navigateToMiniProgramScheme(res.data.contractInfo.destUrl)

      })
  },


  // 跳转签署小程序
  navigateToMiniProgramScheme(scheme) {
    var {
      params,
      message
    } = this.schemeToParams(scheme);
    console.log(params, message)
    if (params) {
      my.navigateToMiniProgram({
        ...params,
        success: (res) => {
          console.log(JSON.stringify(res))
        },
        fail: (res) => {
          console.log(JSON.stringify(res))
        }
      });
    } else {
      fail && fail({
        error: -1,
        errorMessage: `无效的小程序 scheme ${scheme}: ${message}`
      });
    }
  },

  // 将 scheme 转换为 my.navigateToMiniProgram 的参数
  schemeToParams(scheme) {
    console.log(scheme)
    if (!scheme.startsWith('alipays:')) {
      return {
        message: '! 非 alipays: 开头'
      };
    }
    var params = {};
    var parseQuery = (str) => {
      return str.replace(/^.*?\?/, '').split('&').map(s => {
        var p = s.includes('=') ? s.indexOf('=') : s.length;
        return [s.slice(0, p), s.slice(p + 1)].map(decodeURIComponent);
      });
    };
    for (var [k, v] of parseQuery(scheme)) {
      if (k == 'appId') {
        if (v.length != 16) {
          return {
            message: `! 非 16 位 appId '${v}'`
          };
        }
      } else if (k == 'page') {
        k = 'path';
      } else if (k == 'query') {
        var o = {};
        for (var [x, y] of parseQuery(v)) {
          o[x] = y;
        }
        v = o;
      } else {
        return {
          message: `! 不支持参数 '${k}' `
        };
      }
      params[k] = v;
    }
    return {
      params
    };
  },

  // // 跳转签署小程序
  // navigateToMiniProgram(str){
  //     console.log(str)
  //     // str = "alipays://platformapi/startapp?appId=2021001152620480&page=pages/signH5/index&query=signUrl%3Dhttps%253A%252F%252Ftsign.cloud.alipay.com%252Fweb%252FhandMultifileSign%253Ftimestamp%253D1646124493022%2526flowId%253D5fab96b4da5246fdb963b8c0a83c441f%2526accountId%253DDAWRSKNY1%2526sign%253Dcb0fa54e86b4c98b29056fcd81903d43b4caae0664f2bb76bf1d111f2c7af313"
  //     let signUrl = this.getSignUrl(str)
  //     my.navigateToMiniProgram({
  //         appId: '2021001152620480',
  //         path: `pages/signH5/index?signUrl=${signUrl}`,
  //         success: (res) => {
  //             console.log(JSON.stringify(res))
  //         },
  //         fail: (res) => {
  //             console.log(JSON.stringify(res))
  //         }
  //     });
  // },
  // // 格式化链接
  // getSignUrl(aliSchema) {
  //     if(!aliSchema){return  ''}
  //     const querys = aliSchema.split('?')[1].split('&');
  //     const signUrlKeyValue = querys.find((item) => item.includes('query=')).replace('query=', '');
  //     const encodedSignUrl = decodeURIComponent(signUrlKeyValue).replace('signUrl=', '');
  //     return encodedSignUrl
  // },
});